import log from './util.log.js'
import cookies from './util.cookies.js'
import { isNull } from './validate'
let util = {
  cookies,
  log
}
const deepClone = (obj) => {
  var proto = Object.getPrototypeOf(obj)
  return Object.assign({}, Object.create(proto), obj)
}
util.deepClone = deepClone
/**
 * @description 更新标题
 * @param {String} title 标题
 */
util.title = function (titleText) {
  const processTitle = process.env.VUE_APP_TITLE || 'D2Admin'
  window.document.title = `${processTitle}${titleText ? ` | ${titleText}` : ''}`
}

/**
 * @description 打开新页面
 * @param {String} url 地址
 */
util.open = function (url) {
  var a = document.createElement('a')
  a.setAttribute('href', url)
  a.setAttribute('target', '_blank')
  a.setAttribute('id', 'd2admin-menu-link')
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(document.getElementById('d2admin-menu-link'))
}
function getChildren (datas, pid, pidField, idField) {
  var childrens = []
  if (!pidField) {
    pidField = 'parent_id'
  }
  if (!idField) {
    idField = 'id'
  }
  for (var i = 0; i < datas.length; i++) {
    if (datas[i][pidField] === pid) {
      var d = deepClone(datas[i])
      var children = getChildren(datas, datas[i][idField], pidField, idField)
      if (children.length !== 0) {
        d.children = children
      }
      childrens.push(d)
    }
  }
  return childrens
}
// 格式化数据列表为树形结构
function formatList2Tree (datas, pidField, idField) {
  if (!pidField) {
    pidField = 'parent_id'
  }
  if (!idField) {
    idField = 'id'
  }
  var dataList = []
  datas.forEach(d => {
    let hasParent = false
    for (var i = 0; i < datas.length; i++) {
      if (d[pidField] === datas[i][idField]) {
        hasParent = true
        break
      }
    }
    if (!hasParent) {
      var d1 = deepClone(d)
      var children = getChildren(datas, d1[idField], pidField, idField)
      if (children.length !== 0) {
        d1.children = children
      }
      dataList.push(d1)
    }
  })
  return dataList
}
util.formatList2Tree = formatList2Tree

function getMenuChildren (datas, pid, pidField, idField) {
  var childrens = []
  for (var i = 0; i < datas.length; i++) {
    if (datas[i][pidField] === pid) {
      var d = {
        path: datas[i].url,
        title: datas[i].name,
        icon: datas[i].icon
      }
      var children = getMenuChildren(datas, datas[i][idField], pidField, idField)
      if (children.length !== 0) {
        d.children = children
      }
      childrens.push(d)
    }
  }
  return childrens
}

util.formatMenu = function (datas) {
  return getMenuChildren(datas, 0, 'parent_id', 'menu_id')
}

/**
 * 通过用户菜单生成路由信息
 *
 * @param {用户菜单} aMenu
 */
util.formatRoutes = function (aMenu, parentPath) {
  if (isNull(aMenu)) {
    return []
  }
  const aRouter = []
  aMenu.forEach(oMenu => {
    const {
      path,
      component,
      name,
      icon,
      children
    } = oMenu

    if (!isNull(component)) {
      const oRouter = {
        path: parentPath ? parentPath + '/' + path : path,
        component (resolve) {
          let componentPath = ''
          if (component === 'Layout') {
            require(['@/layout/header-aside'], resolve)
            return
          } else {
            componentPath = component
          }
          require([`../${componentPath}.vue`], resolve)
        },
        name: name,
        icon: icon,
        children: isNull(children) ? [] : util.formatRoutes(children, path),
        meta: {
          requiresAuth: true,
          title: name
        }
      }
      aRouter.push(oRouter)
    }
  })
  return aRouter
}
/**
 * 初始化顶部菜单
 * @param {用户菜单} menu
 */
util.initHeaderMenu = function (menu) {
  return getMenu(menu)
}

/**
 * 初始化左边菜单
 * @param {用户菜单} menu
 */
util.initAsideMenu = function (menu) {
  return getMenu(menu)
}
function getMenu (menu, path) {
  if (isNull(menu)) {
    return []
  }
  return menu
  // let list = []
  // for (const m of menu) {
  //   let item = {
  //     path: path ? path + '/' + m.path : m.path,
  //     title: m.name,
  //     icon: m.icon,
  //     url: m.url
  //   }
  //   if (m.children && m.children.length > 0) {
  //     item.children = getMenu(m.children, m.path)
  //   }
  //   list.push(item)
  // }
  // return list
}
function S4 () {
  return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1)
}
// 随机生成UUID
util.guid = () => {
  return (S4() + S4() + '-' + S4() + '-' + S4() + '-' + S4() + '-' + S4() + S4() + S4())
}

// 生成从minNum到maxNum的随机数
util.randomNum = function (minNum, maxNum) {
  switch (arguments.length) {
    case 1:
      return parseInt(Math.random() * minNum + 1, 10)
    case 2:
      return parseInt(Math.random() * (maxNum - minNum + 1) + minNum, 10)
    default:
      return 0
  }
}
// 保存数据
util.SaveData = function (f, data, vm, search) {
  // 保存数据
  f(data)
    .then(res => {
      vm.loading = false
      if (res.status === '200') {
        // this.table.splice(index, 1)
        vm.$message({
          type: 'success',
          message: '更新成功!'
        })
        // 触发数据刷新
        vm.$nextTick(() => {
          search()
        })
      } else {
        vm.$message({
          type: 'error',
          message: res.msg
        })
      }
    })
    .catch(err => {
      vm.loading = false
      vm.$message({
        type: 'error',
        message: '保存失败!'
      })
      console.log('err', err)
    })
}
// 删除数据
util.RemoveData = function (f, data, vm, search) {
  vm.$confirm('此操作将永久删除数据, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
  // 删除数据
    f(data)
      .then(res => {
        vm.loading = false
        if (res.status === '200') {
        // this.table.splice(index, 1)
          vm.$message({
            type: 'success',
            message: '删除成功!'
          })
          // 触发数据刷新
          vm.$nextTick(() => {
            search()
          })
        } else {
          vm.$message({
            type: 'error',
            message: res.msg
          })
        }
      })
      .catch(err => {
        vm.loading = false
        vm.$message({
          type: 'error',
          message: '删除失败!'
        })
        console.log('err', err)
      })
  }).catch(() => {
    vm.$message({
      type: 'info',
      message: '已取消删除'
    })
  })
}
export default util
